package org.example.test03;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class ByteBuddyPanel {

    private final Project project;
    private final JPanel  root = new JPanel(new BorderLayout());

    /* 三个输入控件 */
    private final JTextField classText  = new JTextField();
    private final JTextField methodText = new JTextField();
    private final JTextArea  codeArea   = new JTextArea();

    public ByteBuddyPanel(Project project) {
        this.project = project;
        initUI();
    }

    public JComponent getRoot() {
        return root;
    }

    private void initUI() {
        /* 顶部表单区域 */
        JPanel north = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill   = GridBagConstraints.HORIZONTAL;

        /* 区域 1：类 */
        gbc.gridx = 0; gbc.gridy = 0; gbc.weightx = 0;
        north.add(new JLabel("被拦截的类："), gbc);
        gbc.gridx = 1; gbc.weightx = 1;
        north.add(classText, gbc);

        /* 区域 2：方法 */
        gbc.gridx = 0; gbc.gridy = 1; gbc.weightx = 0;
        north.add(new JLabel("被拦截的方法："), gbc);
        gbc.gridx = 1; gbc.weightx = 1;
        north.add(methodText, gbc);

        /* 区域 3：增强代码 */
        codeArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
        codeArea.setText("System.out.println(\"=== intercepted\");\nreturn method.invoke(obj, args);");
        JScrollPane scroll = new JScrollPane(codeArea);
        scroll.setPreferredSize(new Dimension(500, 200));
        JPanel center = new JPanel(new BorderLayout());
        center.setBorder(BorderFactory.createTitledBorder("3. 增强逻辑（方法体）"));
        center.add(scroll, BorderLayout.CENTER);

        /* 底部按钮 */
        JButton attachButton = new JButton("Attach & Transform");
        attachButton.addActionListener(this::onAttach);
        JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        south.add(attachButton);

        /* 组合 */
        root.add(north, BorderLayout.NORTH);
        root.add(center, BorderLayout.CENTER);
        root.add(south, BorderLayout.SOUTH);
    }

    private void onAttach(ActionEvent e) {
        String cls  = classText.getText().trim();
        String mtd  = methodText.getText().trim();
        String body = codeArea.getText().trim();
        if (StringUtil.isEmptyOrSpaces(cls) || StringUtil.isEmptyOrSpaces(mtd) || StringUtil.isEmptyOrSpaces(body)) {
            Messages.showErrorDialog("请把三项都填完", "Input Error");
            return;
        }
        new AgentRunner(project).run(cls, mtd, body);
    }
}